package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.redis.service.ITravelStatisVORedisService;
import cn.wolfcode.wolf2w.redis.service.ITravelStatisVORedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.redis.vo.TravelStatisVO;
import cn.wolfcode.wolf2w.redis.vo.TravelStatisVO;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.util.DateUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@Service
public class TravelStatisVORedisServiceImpl implements ITravelStatisVORedisService {
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private ITravelService travelService;


    @Override
    public TravelStatisVO getTravelStatisVo(String tid) {
        String vokey = RedisKeys.TRAVEL_STATIS_VO.join(tid);
        //判断vo是否存在
        TravelStatisVO vo = null;

        if (!template.hasKey(vokey)) {
            //如果不存在,初始化
            vo = new TravelStatisVO();
            Travel travel = travelService.get(tid);

            BeanUtils.copyProperties(travel, vo);
            vo.setTravelId(travel.getId());
            template.opsForValue().set(vokey, JSON.toJSONString(vo));
        } else {
            String voStr = template.opsForValue().get(vokey);
            vo = JSON.parseObject(voStr, TravelStatisVO.class);
        }
        return vo;
    }

    @Override
    public void setTravelStatisVo(TravelStatisVO vo) {
        //1.拼接vokey
        String vokey = RedisKeys.TRAVEL_STATIS_VO.join(vo.getTravelId());
        //更新
        template.opsForValue().set(vokey, JSON.toJSONString(vo));
    }

    @Override
    public Boolean travelThumbup(String tid, String uid) {
        //拼接key
        String vokey = RedisKeys.TRAVEL_THUMB.join(uid,tid);
        //判断key是否存在
        if (template.hasKey(vokey)){
            return false;
        }
        //创建实例化对象
        TravelStatisVO vo = new TravelStatisVO();
        //调用点赞数加一
        vo.setThumbsupnum(vo.getThumbsupnum()+1);
        //更新vokey
        this.setTravelStatisVo(vo);
        //设置有效时间
        Date date = new Date();
        Date end = DateUtil.getEndDate(date);
        long between = DateUtil.getDateBetween(date, end);
        //更新
        template.opsForValue().set(vokey,"1" ,between ,TimeUnit.SECONDS );
        return true;
    }




}



